﻿using System;
using Microsoft.Xna.Framework;
using LoA.Shared.Interfaces;
using Microsoft.Xna.Framework.Content;

namespace LoA.Shared {
	public class MapInfo : IMapInfo {
		public MapInfo(string region, Point position, float[ ] heightMap, float scale, int width, int height) {
			this.region = region;
			this.position = position;
			this.heightMap = heightMap;
			this.scale = scale;
			this.width = width;
			this.height = height;
		}

		private readonly string region;
		public string Region { get { return this.region; } }
		private readonly Point position;
		public Point Position { get { return this.position; } }
		private readonly float[ ] heightMap;
		public float[ ] HeightMap { get { return this.heightMap; } }
		private readonly float scale;
		public float Scale { get { return this.scale; } }
		private readonly int width;
		public int Width { get { return this.width; } }
		private readonly int height;
		public int Height { get { return this.height; } }

		#region IEquatable
		public override int GetHashCode( ) {
			return base.GetHashCode( );
		}
		public override bool Equals(object other) {
			if (other.GetType( ).GetInterface(typeof(IMapInfo).Name) != null)
				return this.Equals((other as IMapInfo));
			else
				return false;
		}
		public bool Equals(IMapInfo other) {
			if (other != null)
				return this.Equals(other.Region, other.Position);
			else
				return false;
		}
		public bool Equals(string region, Point position) {
			if (this.Region == region && this.position.Equals(position))
				return true;
			else
				return false;
		}
		public bool Equals(string region, int x, int z) {
			if (this.Region == region && this.position.X == x && this.position.Y == z)
				return true;
			else
				return false;
		}
		#endregion

		/// <summary>
		/// This class will load the HeightMapInfo when the game starts. This class needs 
		/// to match the HeightMapInfoWriter.
		/// </summary>
		public class MapInfoReader : ContentTypeReader<IMapInfo> {
			protected override IMapInfo Read(ContentReader input, IMapInfo existingInstance) {
				string region = input.ReadString( );
				Point position = new Point(input.ReadInt32( ), input.ReadInt32( ));
				float scale = input.ReadSingle( );
				int width = input.ReadInt32( );
				int height = input.ReadInt32( );

				float[ ] heights = new float[width * height];
				for (int i = 0; i < width * height; i++) {
					heights[i] = input.ReadSingle( );
				}

				return new MapInfo(region, position, heights, scale, width, height);
			}
		}

		public Vector2 GetRealPosition( ) {
			return this.Scale * new Vector2(this.Position.X, this.Position.Y) * new Vector2(this.Width - 1, this.Height - 1);
		}
	}
}